<template>
	<view class="register-container">
		<view class="u-m-b-30" v-if="registerType === 0">
			<fui-icon name="warning-fill" color="#ff551a" :size="30" class="u-m-r-10"> </fui-icon> 
			<text style="color:#ff551a;font-size: 28rpx;" > 
				本应用内容涉及酒类相关信息，请确认您已满18周岁并确认提交信息真实有效。请您切勿向未成年人分享此账号内容，禁止上传不理性饮酒未成年人内容、违反社会公序良俗及侵权内容，平台保留删除此类内容的权利。
			</text>
		</view>
		<view class="u-p-20 u-flex u-row-between u-m-b-30" style="border-radius: 10rpx;background-color: #f6f6f6;" v-if="userFrom.IdType!==0">
			<view class="u-flex-1 u-font-30 u-line-1" style="color: #666;">
				已选:{{authText[userFrom.IdType-1]}}
			</view>
			<view class="u-flex" @click="userFrom.IdType = 0">
				<text class="u-m-r-10 u-font-30" style="color: #666;"> 重新选择</text>
				<fui-icon name="arrowright" size="30" color="#666"></fui-icon>
			</view>
		</view>
		<view class="u-font-36" style="font-weight: 500;">
			{{titleShow}}
		</view> 
		<!-- 切换tabbar 自动识别或手动输入 -->
		<view class="register-header u-flex u-row-between" v-if="(registerType === 0&&userFrom.IdType === 1)||registerType === 1">
			<view :class="['u-flex','header-item', 'u-m-r-42', 'u-row-center', {'header-item-active':tabbarIndex===0}]" @click="tabbarChange(0)">
				<fui-icon name="camera" size="42" :color="tabbarIndex ===0?'#ff551a':'#666'"></fui-icon>
				<text class="u-font-32 u-m-l-20" :style="{'color':tabbarIndex === 0?'#ff551a':'#666'}">自动识别</text>
				<view class="mark-yes u-flex u-row-center" v-show="tabbarIndex===0">
					<fui-icon name="check" size="30" color="#fff"></fui-icon>
				</view>
			</view>
			<view :class="['u-flex','header-item', 'u-row-center', {'header-item-active':tabbarIndex===1}]" @click="tabbarChange(1)">
				<fui-icon name="edit" size="42" :color="tabbarIndex === 1?'#ff551a':'#666'"></fui-icon>
				<text class="u-font-32 u-m-l-20" :style="{'color':tabbarIndex === 1?'#ff551a':'#666'}">手动填写</text>
				<view class="mark-yes u-flex u-row-center" v-show="tabbarIndex===1">
					<fui-icon name="check" size="30" color="#fff"></fui-icon>
				</view>
			</view>
		</view>
		<!-- 实名认证部分 --> 
		<view v-if="registerType === 0">
			<view class="auth-type-list" v-if="userFrom.IdType === 0">
				<view class="auth-type-item u-flex u-row-between" v-for="(item,index) in authIcon" @click="userFrom.IdType = index+1">
					<view class="u-flex u-flex-1">
						<image :src="`/static/common/${item}.png`" class="auth-type-image"></image>
						<text class="u-line-1 u-flex-1 u-font-30">{{authText[index]}}{{index===0?'（自动认证）':'（人工认证）'}}</text>
					</view>
					<fui-icon name="arrowright" size="50"></fui-icon>
				</view>
			</view>
			<view v-else-if="userFrom.IdType === 1">
				<fui-upload immediate 
				 v-if="tabbarIndex === 0"
					:url="baseUrl + 'api/Resource/Upload'" ref="upload"
					:header="header"
					:height="264"
					:width="'100%'"
					max="1"
					@success="onFrontSuccess" 
					@delete="onFrontRemove"
				>
					<view  class="upload-area u-flex u-row-center" style="flex-direction: column;">
						<fui-icon name="camera" color="#666" size="46"></fui-icon>
						<view class="u-font-26 u-text-center"  style="color: #666;width: 100%;">上传身份证正面照片</view>
					</view>
				</fui-upload>
				<fui-form ref="userFormRef">
					<fui-input required label="姓名"  placeholder="请输入姓名" v-model="userFrom.realname" :disabled="idCardIdentify" disabledStyle></fui-input>
					<fui-input required label="身份证号" placeholder="请输入身份证号" v-model="userFrom.idCardNo" :disabled="idCardIdentify" disabledStyle></fui-input>
				</fui-form>
				<view class="u-m-t-50">
					<image src="/static/common/doushou.png" style="height: 250rpx;width: 100%;"></image>
				</view>
			</view>
			<view v-else>
				<fui-form ref="userFormRef" >
					<fui-input required label="姓名"  placeholder="请输入姓名" v-model="userFrom.realname"  ></fui-input>
					<fui-input required label="证件号" placeholder="请输入证件号" v-model="userFrom.idCardNo" ></fui-input>
					<fui-upload immediate
						class="u-m-t-20"
						:url="baseUrl + 'api/Resource/Upload'"
						:header="header"
						:height="264"
						:width="'100%'"
						max="1"
						@success="e=>otherImageSuccess(e,1)" 
						@delete="otherImageRemove(1)"
						>
						<view  class="upload-area u-flex u-row-center" style="flex-direction: column;">
							<fui-icon name="camera" color="#666" size="46"></fui-icon>
							<view class="u-font-26 u-text-center"  style="color: #666;width: 100%;">上传证件照1</view>
						</view>
					</fui-upload>
					<fui-upload immediate
						:url="baseUrl + 'api/Resource/Upload'" 
						:header="header"
						:height="264"
						:width="'100%'"
						max="1"
						@success="e=>otherImageSuccess(e,2)" 
						@delete="otherImageRemove(2)"
						>
						<view  class="upload-area u-flex u-row-center" style="flex-direction: column;">
							<fui-icon name="camera" color="#666" size="46"></fui-icon>
							<view class="u-font-26 u-text-center"  style="color: #666;width: 100%;">上传证件照2</view>
						</view>
					</fui-upload>
				</fui-form>
				<view class="u-m-t-50">
					<image src="/static/common/doushou.png" style="height: 250rpx;width: 100%;"></image>
				</view>
			</view>
		
		</view>
		<!-- 企业注册部分 -->
		<view v-if="registerType === 1">
			<fui-upload immediate
				:url="baseUrl + 'api/Resource/Upload'" 
				:header="header"
				:height="264"
				:width="'100%'"
				max="1"
				v-if="tabbarIndex === 0"
				@success="onBussnessSuccess" 
				@delete="onBusinessRemove"
			>
				<view  class="upload-area u-flex u-row-center" style="flex-direction: column;">
					<fui-icon name="camera" color="#666" size="46"></fui-icon>
					<view class="u-font-26 u-text-center"  style="color: #666;width: 100%;">上传营业执照</view>
				</view>
			</fui-upload>
			 <!-- v-if="tabbarIndex === 0&&idBusinessIdentify" -->
			<fui-form  ref="businessFormRef">
				<fui-input required label="企业名称"  placeholder="请输入企业名称" v-model="businessForm.name" labalTop   ></fui-input>
				<fui-input required label="统一社会信用代码"  placeholder="请输入企业编号" v-model="businessForm.unifiedSocialCreditCode"   labalTop   ></fui-input>
				<fui-input required label="法定代表人姓名"  placeholder="请输入法人姓名" v-model="businessForm.legalPersonName"   labalTop ></fui-input>
				<fui-input @click="showAddressPickerFn()" required label="企业经营区域"  placeholder="省/市/区（县）" v-model="businessForm.regionName"  
				 labalTop ></fui-input>
			</fui-form>
			<fui-bottom-popup :show="pickerShow">
				<view class="fui-scroll__wrap">
					<view class="fui-title">请选择企业经营区域</view>
					<fui-cascader activeColor="#ffbb1a" ref="addressPicker" :textKey="'name'" v-if="pickerShow" :valueKey="'id'" stepLoading @change="addressChange" @complete="addressComplete" :options="addressData"></fui-cascader>
					<view class="fui-icon__close" @tap.stop="pickerShow = false">
						<fui-icon name="close" :size="48"></fui-icon>
					</view>
				</view>
			</fui-bottom-popup>
		</view>
	</view>
</template>

<script setup>
	import {useUserStore} from '@/store/user.js';
	import {ref,reactive,computed} from 'vue';
	import newHttp from '@/utils/request/newRequest.js';
	const userStore = useUserStore(); // 在 setup 中使用 store
	const authText = ['身份证','港澳台居民居住证','外国人永久居留身份证','护照'];
	const authIcon = ['authIC','authHK','authWGR','authHZ'];
	const {registerType} = defineProps(['registerType']); //0 个人实名认证  1 企业
	const header = {Authorization: 'Bearer ' + userStore.token}; //上传图片Token
	const idCardIdentify = ref(false); //是否来自自动身份证识别
	const userFrom = reactive({ //实名认证表单
		id:userStore.id,
		realname: '',
		idCardNo: '',
		IdType:0
	})
	const tabbarIndex = ref(0); //0 自动识别  1 手动输入
	const pickerShow = ref(false);
	const addressData = reactive([]);
	const region = ref('');
	const defaultRegion = ref([]);
	const defaultArea = ref([]);
	const businessForm = reactive({
		name: '',
		unifiedSocialCreditCode: '',
		legalPersonName: '',
		regionId: '',
		regionName:'',
	});
	const addressPicker = ref(null);
	const titleShow = computed(()=>{
		if(registerType === 0&&userFrom.IdType === 0){
			return '选择证件类型';
		}
		if(registerType === 0&&userFrom.IdType !== 0){
			return '个人信息';
		}
		if(registerType === 1){
			return '营业执照信息';
		}
	})
	async function showAddressPickerFn(){
		// setRequestData
		console.log(addressData.length);
		if(addressData.length ===0){
			let res = await newHttp.get('api/Region');
			if(res.code === 200){
				addressData.push(...res.data)
			}
		}
		pickerShow.value = true;
	};
	async function addressChange(val){
		console.log('触发change',arguments);
		if(val.depth!==3){
			let res = await newHttp.get('api/Region?id='+val.id);
			if(res.code ===200){
				addressPicker.value.setRequestData(res.data, val.layer)
			}
		}else{
			addressPicker.value.end()
		}
	};
	function addressComplete(val){
		businessForm.regionName = val.name.join('');
		businessForm.regionId = val.id[val.id.length-1];
		pickerShow.value = false;
	};
	async function onBussnessSuccess(e){
		let imageData = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}");
		if(imageData.code ===200){
			uni.showLoading({
				title:'正在识别...'
			})
		}else{
			return uni.$fui.toast('图片上传失败');
		}
		const res = await newHttp.get('api/ThirdParty/ali/recognizeBusinessLicense', { params: {  resourceId: imageData.data[0].id } });
		uni.hideLoading();
		if(res.code === 200){
			businessForm.name = res.data.name;
			businessForm.unifiedSocialCreditCode = res.data.registerNumber;
			businessForm.legalPersonName = res.data.legalPerson;
			tabbarIndex.value = 1;
		}else{
			uni.$fui.toast('识别失败，请重新上传或手动输入营业执照信息');
		}
	};
	function onBusinessRemove(){
		businessForm.name = '';
		businessForm.unifiedSocialCreditCode = '';
		businessForm.legalPersonName = '';
	};
	// 切换证件输入方式
	function tabbarChange(val){
		tabbarIndex.value = val;
		if(registerType == 0){
			if(val === 0){
				userFrom.realname = '';
				userFrom.idCardNo = '';
			}
			idCardIdentify.value = false;
		}
	}
	// 身份证正面上传并识别
	async function onFrontSuccess(e){
		let imageData = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}");
		if(imageData.code ===200){
			uni.showLoading({
				title:'正在识别...'
			})
		}else{
			return uni.$fui.toast('图片上传失败');
		}
		const res = await newHttp.get('api/ThirdParty/ali/recognizeIdentity', { params: { side: 'face', resourceId: imageData.data[0].id } });
		uni.hideLoading();
		if(res.code === 200&&res.data.frontResult){
			let frontResult = res.data.frontResult;
			idCardIdentify.value = true;
			userFrom.realname = frontResult.name;
			userFrom.idCardNo = frontResult.idNumber;
		}else{
			idCardIdentify.value = false;
			uni.$fui.toast('识别失败，请重新上传或手动输入身份证信息');
		}
		
	};
	// 身份证图片删除
	function onFrontRemove(){
		userFrom.realname = '';
		userFrom.idCardNo = '';
		idCardIdentify.value = false;
	};
	// 证件照上传（除了身份证的其他证件）
	function otherImageSuccess(e,type){
		let imageData = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}");
		if(imageData.code ===200){
			if(type ===1){
				userFrom.faceResourceId = data.data[0].id;
			}else{
				userFrom.backResourceId = data.data[0].id;
			}
		}else{
			return uni.$fui.toast(`证件照${type}上传失败`);
		}
	};
	// 证件照删除
	function otherImageRemove(type){
		if(type ===1){
			userFrom.faceResourceId = '';
		}else{
			userFrom.backResourceId = '';
		}
	};
	const userRules=[
		{
			name: "realname",
			rule: ["required"],
			msg: ["请输入真实姓名"]
		},
		{
			name: "idCardNo",
			rule: ["isIdCard","required"],
			msg: ["请输入正确的身份证号码"]
		}
	];
	const userFormRef = ref(null);
	function userValidator(){
		if(userFrom.IdType === 0){
			uni.$fui.toast('请选择证件类型填写')
			return false;
		}else if(userFrom.IdType === 1&&tabbarIndex.value === 0&&!idCardIdentify.value){
			uni.$fui.toast('请上传身份证照自动识别，或手动填写个人信息')
			return false;
		}
		return userFormRef.value.validator(userFrom, userRules)
		.then(res => {
			return res.isPassed;
		}).catch(err => {
			console.log(err)
			return false;
		})
	}
	const shopRules=[
		{
			name: "name",
			rule: ["required"],
			msg: ["请输入企业名称"]
		},
		{
			name: "unifiedSocialCreditCode",
			rule: ["required"],
			msg: ["请输入企业营业执照编码"]
		},
		{
			name: "legalPersonName",
			rule: ["required"],
			msg: ["请输入企业法人名称"]
		},
		{
			name: "regionId",
			rule: ["required"],
			msg: ["请选择企业经营区域"]
		},
	];
	const businessFormRef = ref(null);
	function shopValidator(){
		return businessFormRef.value.validator(businessForm, shopRules)
		.then(res => {
			return res.isPassed;
		}).catch(err => {
			return false;
		})
	};
	defineExpose({ userValidator,userFrom,shopValidator,businessForm });

</script>

<style lang="scss" scoped>
	page{
		background-color: #fff !important;
	}
	.register-container{
		overflow: hidden;
		.auth-type-list{
			padding: 30rpx 0;
			.auth-type-item{
				background-color: #f6f6f6;
				border-radius: 12rpx;
				padding: 25rpx 30rpx;
				margin-bottom: 20rpx;
				.auth-type-image{
					width: 68rpx;
					height: 68rpx;
					margin-right: 10rpx;
				}
			}
		}
		.register-header{
			margin: 28rpx 0;
			.header-item{
				flex:1;
				box-sizing: border-box;
				padding: 30rpx 0;
				border: 2rpx solid #CCCCCC;
				border-radius: 8rpx;
				color: #666;
			}
			.header-item-active{
				border: 2rpx solid #FF551A;
				background-color: #FFEEE8;
				position: relative;
				color: #FF551A;
				.mark-yes{
					position: absolute;
					width: 34rpx;
					height: 34rpx;
					background-color: #ff551a;
					bottom: 0;
					right: 0;
					border-radius: 5rpx;
					border-bottom-right-radius: 9rpx;
				}
				
			}
		}
	}
	.fui-scroll__wrap {
		padding-top: 30rpx;
		position: relative;
	}
	
	.fui-title {
		font-size: 30rpx;
		font-weight: bold;
		text-align: center;
		padding-bottom: 24rpx;
	}
	
	.fui-icon__close {
		position: absolute;
		top: 24rpx;
		right: 24rpx;
	}
</style>